package com.smzd.framework.system.business;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.smzd.core.dao.IDao;
import com.smzd.framework.core.business.AbstractFGService;
import com.smzd.framework.system.dao.GroupDao;
import com.smzd.framework.system.domain.Group;
import com.smzd.framework.system.domain.Meeting;
import com.smzd.framework.utils.db.FGRowConverter;
import com.smzd.framework.utils.db.ORPage;

@Service
public class GroupService extends AbstractFGService<Group> {
	@Autowired
	private GroupDao dao;

	@Override
	protected IDao<Group> getDao() {
		return dao;
	}

	@Override
	public FGRowConverter<Group> getConverter() {
		return GroupService.converter;
	}

	private static FGRowConverter<Group> converter = new FGRowConverter<Group>() {
		@Override
		public Object[] convert(Group elem) {
			String ownerName = elem.getOwner() == null ? null : elem.getOwner()
					.getName();
			Object[] fields = new Object[] { 
					elem.getId(), 
					elem.getName(),
					elem.getDescription(),
					ownerName
			};
			return fields;
		}
	};
	private static FGRowConverter<Group> checkedConverter = new FGRowConverter<Group>() {
		@Override
		public Object[] convert(Group elem) {
			String ownerName = elem.getOwner() == null ? null : elem.getOwner()
					.getName();
			Object[] fields = new Object[] { 
					elem.getId(), 
					elem.getName(),
					elem.getDescription(),
					ownerName,
					elem.getChecked()
			};
			return fields;
		}
	};

	public String getUserGroupListDataJson(ORPage<Meeting, Group> page) {
		dao.getUserGroupListByPage(page);
		return page.toFlexiGridJsonString(checkedConverter);
	}

	public void appendUserToGroups(int userId, Integer... groupId){
		dao.addUserToGroups(userId, groupId);
	}
	public void removeUserFromGroups(int userId, Integer... groupId){
		dao.removeUserFromGroups(userId, groupId);
	}
	public void saveUserGroups(int userId, String groupIds) {
		String[] ids = groupIds.split(",");
		List<Integer> toAdd = new ArrayList<>();
		List<Integer> toDel = new ArrayList<>();
		for (String id : ids) {
			int rid = Integer.parseInt(id);
			if (rid < 0) {
				toDel.add(-rid);
			} else {
				toAdd.add(rid);
			}
		}
		if (toAdd.size() > 0) {
			Integer[] add = new Integer[toAdd.size()];
			dao.addUserToGroups(userId, toAdd.toArray(add));
		}
		if (toDel.size() > 0) {
			Integer[] del = new Integer[toDel.size()];
			dao.removeUserFromGroups(userId, toDel.toArray(del));
		}
	}
	
	public List<Group> getGroupsByUserId(int uid){
		return dao.getGroupsByUserId(uid);
	}
}
